#include "head_client.h"

int recvFile(int sockfd,char* unuse)//冗余设计
{
    train_t train;
    bzero(&train, sizeof(train));

    //收文件名
    recvn(sockfd, &train.length, sizeof(train.length));
    recvn(sockfd, train.data, train.length);
    int fd = open(train.data, O_WRONLY | O_TRUNC | O_CREAT, 0666);

    //保存文件名，用于MD5校验
    train_t train_savefilename;
    train_savefilename.length = train.length;
    strcpy(train_savefilename.data,train.data);

    printf(" filename = %s\n",train.data);
    off_t filesize;

    //收文件大小
    recvn(sockfd, &train.length, sizeof(train.length));
    recvn(sockfd, train.data, train.length);
    memcpy(&filesize, train.data, sizeof(off_t));

    printf("filesize = %ld\n", filesize);
    off_t cursize = 0;
    off_t lastsize = 0;

    //循环收取
    while (1)
    {
        bzero(&train, sizeof(train));
        recvn(sockfd, &train.length, sizeof(train.length));
        if (train.length != 1000)
        {
            printf("train.length = %d\n", train.length);
        }
        if (train.length == 0)
        {
            break;
        }
        recvn(sockfd, train.data, train.length);
        write(fd, train.data, train.length);
        cursize += train.length;
        if (cursize - lastsize > filesize / 1000)
        {
            printf("%5.2lf%%\r", 100.0 * cursize / filesize);
            fflush(stdout);
            lastsize = cursize;
        }
    }
    printf("100.00%%\n");
    close(fd);
    
    int fd2 = open(train_savefilename.data,O_RDONLY);
    md5(fd2,"unuse");
    close(fd2);
    return 0;
}